<?php

namespace App\Http\Controllers\Api\Members;

use App\Http\Controllers\Controller;
use App\Libs\Strategy\Context;
use App\Models\Members;
use App\Models\Members\MemberDraw;
use App\Models\Members\MemberPipeline;
use Illuminate\Http\Request;

class MemberDrawController extends Controller
{
    protected $memberDraw;

    public function __construct()
    {
        $this->memberDraw = new Context(new MemberDraw());
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $list = $this->memberDraw->display($request->limit, function($query) use ($request){
            $query->with('member', 'bank');
            if($request->keyword){
                $query->whereHas('member', function($member){
                    $member->where('mobile', 'like', \request()->keyword.'%')->orWhere('nickname','like',\request()->keyword.'%');
                });
            }
            if(!is_null($request->status)){

                $query->where('status', \request()->status);
            }

            return $query;
        });
        return $list;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $post = $request->all();

        $draw = $this->memberDraw->find($id);
        $draw->status = $post['status'];
        $draw->action_at = now();

        if(!$draw->save()){
            return $this->error('操作失败');
        }

        // 拒绝将金额退还
        if($post['status'] == 2){

            Members::where(['id'=> $draw->member_id])->increment('earnings', $draw->money);
            MemberPipeline::MemberAddPipeline($draw->member_id,$draw->money,9,'收益提现拒绝返还收益-'.$draw->money,1, 3);
            $msg = "拒绝";
        }else {

            $msg = "通过";
        }

        return $this->success(['message'=>$msg.'成功']);
    }
}
